package cn.iocoder.yudao.module.erp.controller.admin.marketcontract;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.erp.controller.admin.finance.vo.payment.ErpFinancePaymentRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.order.ErpPurchaseOrderRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.marketcontract.MarketContractProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOrderItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.purchase.ErpSupplierService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.erp.controller.admin.marketcontract.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.marketcontract.ErpMarketContractDO;
import cn.iocoder.yudao.module.erp.service.marketcontract.ErpMarketContractService;

@Tag(name = "管理后台 - 市场管理合同信息")
@RestController
@RequestMapping("/erp/market-contract")
@Validated
public class ErpMarketContractController {

    @Resource
    private ErpMarketContractService marketContractService;
    @Resource
    private ErpProductService productService;
    @Resource
    private ErpSupplierService supplierService;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建市场管理合同信息")
    @PreAuthorize("@ss.hasPermission('erp:market-contract:create')")
    public CommonResult<Long> createMarketContract(@Valid @RequestBody ErpMarketContractSaveReqVO createReqVO) {
        return success(marketContractService.createMarketContract(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新市场管理合同信息")
    @PreAuthorize("@ss.hasPermission('erp:market-contract:update')")
    public CommonResult<Boolean> updateMarketContract(@Valid @RequestBody ErpMarketContractSaveReqVO updateReqVO) {
        marketContractService.updateMarketContract(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除市场管理合同信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:market-contract:delete')")
    public CommonResult<Boolean> deleteMarketContract(@RequestParam("id") Long id) {
        marketContractService.deleteMarketContract(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除市场管理合同信息")
                @PreAuthorize("@ss.hasPermission('erp:market-contract:delete')")
    public CommonResult<Boolean> deleteMarketContractList(@RequestParam("ids") List<Long> ids) {
        marketContractService.deleteMarketContractListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得市场管理合同信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:market-contract:query')")
    public CommonResult<ErpMarketContractRespVO> getMarketContract(@RequestParam("id") Long id) {
        ErpMarketContractDO marketContract = marketContractService.getMarketContract(id);
        if (marketContract == null) {
            return success(null);
        }
        List<MarketContractProductDO> itemList = marketContractService.getMarketContractItemsByContractId(id);
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(itemList, MarketContractProductDO::getProductId));
        return success(BeanUtils.toBean(marketContract, ErpMarketContractRespVO.class, marketContractVO ->
                        marketContractVO.setItems(BeanUtils.toBean(itemList, ErpMarketContractRespVO.ProductItem.class, item -> {
                            MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                                    .setProductTypeName(product.getCategoryName()).setProductUnitName(product.getUnitName()));
                        }
                ))));
    }

    @GetMapping("/page")
    @Operation(summary = "获得市场管理合同信息分页")
    @PreAuthorize("@ss.hasPermission('erp:market-contract:query')")
    public CommonResult<PageResult<ErpMarketContractRespVO>> getMarketContractPage(@Valid ErpMarketContractPageReqVO pageReqVO) {
        PageResult<ErpMarketContractDO> pageResult = marketContractService.getMarketContractPage(pageReqVO);
        return success(buildPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出市场管理合同信息 Excel")
    @PreAuthorize("@ss.hasPermission('erp:market-contract:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMarketContractExcel(@Valid ErpMarketContractPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpMarketContractRespVO> list = buildPage(marketContractService.getMarketContractPage(pageReqVO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "市场管理合同信息.xls", "数据", ErpMarketContractRespVO.class, list);
    }

    private PageResult<ErpMarketContractRespVO> buildPage(PageResult<ErpMarketContractDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.3 供应商信息
        Map<Long, ErpSupplierDO> supplierMap = supplierService.getSupplierMap(
                convertSet(pageResult.getList(), ErpMarketContractDO::getPartyB));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), document -> Long.parseLong(document.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpMarketContractRespVO.class, payment -> {
            MapUtils.findAndThen(supplierMap, payment.getPartyB(), supplier -> payment.setSupplierName(supplier.getName()));
//            MapUtils.findAndThen(userMap, Long.parseLong(payment.getCreator()), user -> payment.setCreatorName(user.getNickname()));
        });

    }



}
